package cn.hdu.charge.dao;

import cn.hdu.charge.domain.User;
import cn.hdu.utils.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigDecimal;
import java.sql.SQLException;

/**
 * 用户模块持久层
 */
public class UserDao {
    private QueryRunner qr = new TxQueryRunner();

    public void add(User user) throws SQLException {
        String sql = "insert into user(userId, mobile, password, balance) " +
                "values (?,?,?,?)";
        Object[] params = {user.getUserId(), user.getMobile(),
                user.getPassword(), user.getBalance()};
        qr.update(sql, params);
    }

    public User findByMobileAndPassword(String mobile, String password) throws SQLException {
        String sql = "SELECT * FROM user WHERE mobile=? AND password=?";
        return qr.query(sql, new BeanHandler<>(User.class), mobile, password);
    }

    public boolean findByuserIdAndPassword(String userId, String password) throws SQLException {
        String sql = "select count(*) from user where userId=? AND password=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), userId, password);
        return number.intValue()>0;
    }

    public void updatePassword(String userId , String password) throws SQLException {
        String sql = "UPDATE user SET password=? WHERE userId=?";
        qr.update(sql, password, userId);
    }

    public void chargeBlance(String userId, BigDecimal blance) throws SQLException {
        String sql = "UPDATE user SET blance=? WHERE userId=?";
        qr.update(sql, blance, userId);
    }

    /**
     * 校验mobile是否注册
     */
    public boolean ajaxValidateMobile(String mobile) throws SQLException {
        String sql = "select count(1) from user where mobile=?";
        Number number = (Number) qr.query(sql, new ScalarHandler(), mobile);
        return number.intValue() == 0;
    }

}
